import { Alert } from "react-native";
import axios from 'axios';
import StorageUtil from '../common/storageUtil';
import Toast from '../common/Toast';
import NavigationService from '../common/NavigationService';

export default class Axios {

	static ajax(options){
		console.log("ajax");
		console.log(options);

		return new Promise((resolve,reject)=>{

			StorageUtil.getItem(global.Constants.UESR_TOKEN).then((val)=>{
				axios({
					method:'post',
					baseURL: global.Constants.BASE_URL,
					url:options.url,
					data:options.data,
					headers:{
						'Content-Type': 'application/json',
						token:val.token
					}
				}).then((response)=>{
					let error;
					if(response.status === 200){
						let res = response.data;
						if(res.code === 200){
							StorageUtil.setItem(global.Constants.UESR_TOKEN, {token:res.token});
							resolve(res.data);
						}else if(res.code === 400){
							StorageUtil.setItem(global.Constants.UESR_TOKEN, {token:res.token});
							resolve(res.message);
						}else if(res.code === 501){
							NavigationService.navigate('Auth');
							Toast.show(global.Constants.RES_CODE[res.code]);
						}else{
							Toast.show(global.Constants.RES_CODE[res.code]);
						}
					}else{
						console.log("网络异常("+response.status+")");
						Toast.show('网络异常');
					}
				}).catch((error)=>{
					console.log("系统异常("+error+")");
					Toast.show('系统异常');
		    })
			});

		});

	}

	static login(options){
		console.log("login");
		console.log(options);

	  return new Promise((resolve,reject)=>{
	    axios({
	      method:'post',
	      baseURL: global.Constants.BASE_URL,
	      url:options.url,
	      data:options.data,
	      headers:{
	        'Content-Type': 'application/json'
	      }
	    }).then((response)=>{
	      if(response.status === 200){
	        let res = response.data;
	        if(res.code === 200){
						StorageUtil.setItem(global.Constants.UESR_TOKEN, {token:res.token});
	          resolve(res.data);
	        }else if( res.code===400 ){
						Toast.show(res.message);
					}else{
						Toast.show(global.Constants.RES_CODE[res.code]);
					}
	      }else{
					console.log("网络异常("+response.status+")");
					Toast.show('网络异常');
	      }
	    }).catch((error)=>{
				console.log("系统异常("+error+")");
				Toast.show('系统异常');
	    })
	  })
	}


}
